package com.security.control.browser.validate.impl;

import com.security.control.core.validate.support.ValidateCodeType;
import com.security.control.core.validate.support.ValidateCode;
import com.security.control.core.validate.ValidateCodeRepository;
import org.springframework.social.connect.web.HttpSessionSessionStrategy;
import org.springframework.social.connect.web.SessionStrategy;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;

/**
 * @author imoot@gamil.com
 * @date 2018/12/23 0023 11:14
 * ---基于session的验证码存取器
 */
@Component
public class SessionValidateCodeRepository implements ValidateCodeRepository {

    //验证码放入session时的前缀
    private String SESSION_KEY_PREFIX = "SESSION_KEY_FOR_CODE_";

    //操作session的工具类
    private SessionStrategy sessionStrategy = new HttpSessionSessionStrategy();

    /**
     * @param request
     * @param code
     * @param validateCodeType
     * 把验证码保存在session中
     */
    @Override
    public void save(ServletWebRequest request, ValidateCode code, ValidateCodeType validateCodeType) {
        sessionStrategy.setAttribute(request, structureSessionKey(request, validateCodeType), code);
    }

    /**
     * @param request
     * @param validateCodeType
     * @return ValidateCode
     * 根据sessionkey取出验证码
     */
    @Override
    public ValidateCode get(ServletWebRequest request, ValidateCodeType validateCodeType) {
        return (ValidateCode) sessionStrategy.getAttribute(request, structureSessionKey(request, validateCodeType));
    }

    /**
     * @param request
     * @param codeType
     * 根据sessionkey移除验证码
     */
    @Override
    public void remove(ServletWebRequest request, ValidateCodeType codeType) {
        sessionStrategy.removeAttribute(request, structureSessionKey(request, codeType));
    }

    /**
     * @param request
     * @param validateCodeType
     * @return String
     * 构建验证码存放在session中的key
     */
    private String structureSessionKey(ServletWebRequest request, ValidateCodeType validateCodeType) {
        return SESSION_KEY_PREFIX + validateCodeType.toString().toUpperCase();
    }
}
